package com.css.openapi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.css.common.core.constant.AppCons;
import com.css.common.core.constant.FpkjztEnum;
import com.css.common.core.constant.ValidGroup;
import com.css.common.core.enums.*;
import com.css.common.core.utils.*;
import com.css.openapi.BO.*;
import com.css.openapi.entity.JctyDdmx;
import com.css.openapi.entity.JctyDdxx;
import com.css.openapi.feign.ZfjkpPtCommonClient;
import com.css.openapi.mapper.JctyDdxxMapper;
import com.css.openapi.service.JctyDdmxService;
import com.css.openapi.service.JctyDdxxService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.groups.Default;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;


/**
 * 基础通用订单信息表(JctyDdxx)表服务实现类
 *
 * @author xiaolongwei
 * @since 2024-12-09 15:56:28
 */
@Slf4j
@Service("jctyDdxxService")
public class JctyDdxxServiceImpl extends ServiceImpl<JctyDdxxMapper, JctyDdxx> implements JctyDdxxService {


    @Resource
    private JctyDdmxService jctyDdmxService;

    @Resource
    private ZfjkpPtCommonClient zfjkpPtCommonClient;


    @Override
    public void fillBean(JctyDdxx jctyDdxx, ExtraV2VO extraVO) {
        if (Objects.isNull(jctyDdxx)) {
            jctyDdxx = new JctyDdxx();
        }
        jctyDdxx.setGfzrr(extraVO.getGmfzrrbz());
        jctyDdxx.setGmfdh(extraVO.getGmfdh());
        jctyDdxx.setGmfdz(extraVO.getGmfdz());
        jctyDdxx.setGmfkhh(extraVO.getGmfkhh());
        jctyDdxx.setGmfmc(extraVO.getGmfnsrmc());
        jctyDdxx.setGmfnsrsbh(extraVO.getGmfnsrsbh());
        jctyDdxx.setGmfyhzh(extraVO.getGmfzh());
        jctyDdxx.setKpNotifyUrl(extraVO.getCallBackUrl());
        jctyDdxx.setOrderNo(extraVO.getMerchantOrderId());
        jctyDdxx.setCjsj(LocalDateTime.now());
        jctyDdxx.setScbj("0");
        jctyDdxx.setBz(extraVO.getBz());
        jctyDdxx.setFppz(extraVO.getFppz());
    }

    /**
     * 开具蓝色发票
     *
     * @param param 参数
     * @return {@link IssueBlueInvoiceResponse }
     */
    @Override
    @Transactional
    public IssueBlueInvoiceResponse issueBlueInvoice(IssueBlueInvoiceRequest param) {
        IdempotentUtil.verify("GBXU:" + param.getMerchantOrderId(), IdempotentUtil.IDEMPOTENT_TIME);
        IssueBlueInvoiceResponse response = new IssueBlueInvoiceResponse();
        Set<String> error = ValidatorUtil.beanValidate(param, Default.class);
        if (!error.isEmpty()) {
            response.setErrCode("9001");
            response.setErrInfo(CollectionUtil.join(error, "，"));
            return response;
        }
        response.setMerchantOrderId(param.getMerchantOrderId());
        boolean exists = lambdaQuery().eq(JctyDdxx::getOrderNo, param.getMerchantOrderId()).exists();
        if (exists) {
            response.setErrCode("9999");
            response.setErrInfo("商户订单号已存在");
            return response;
        }
        try {
            String ywlx = YwlxEnum.YWLX_JCTY.getDm();
            //添加订单
            JctyDdxx ddxx = new JctyDdxx();
            ddxx.setDdid(IdUtils.createOrderId(ywlx));
            ddxx.setJyno(ddxx.getDdid());
            ddxx.setOrderNo(param.getMerchantOrderId());
            ddxx.setShh("empty");
            ddxx.setZdh("empty");
            ddxx.setXsfsh(param.getXsfnsrsbh());
            ddxx.setXsfnsrmc(param.getXsfmc());
            ddxx.setGfzrr("Y");
            ddxx.setGmfdh(param.getGmfdh());
            ddxx.setGmfdz(param.getGmfdz());
            ddxx.setGmfkhh(param.getGmfkhh());
            ddxx.setGmfmc(param.getGmfnsrmc());
            ddxx.setGmfnsrsbh(param.getGmfnsrsbh());
            ddxx.setGmfyhzh(param.getGmfzh());
            ddxx.setCjr(param.getXsfnsrsbh());
            //添加订单明细
            BigDecimal zjshj = BigDecimal.ZERO;
            BigDecimal zje = BigDecimal.ZERO;
            BigDecimal zse = BigDecimal.ZERO;
            List<JctyDdmx> ddmxs = new ArrayList<>();
            List<IssueBlueInvoiceRequest.OrderDetail> ddmx = param.getDdmx();
            for (IssueBlueInvoiceRequest.OrderDetail orderDetail : ddmx) {
                JctyDdmx jctyDdmx = new JctyDdmx();
                jctyDdmx.setDdid(ddxx.getDdid());
                jctyDdmx.setMxxh(orderDetail.getMxxh());
                jctyDdmx.setSlzsl(orderDetail.getSlzsl());
                jctyDdmx.setSphfflbm(orderDetail.getSphfwflbm());
                jctyDdmx.setXmmc(orderDetail.getXmmc());
                jctyDdmx.setSl(orderDetail.getNum());
                jctyDdmx.setDw(orderDetail.getDw());
                jctyDdmx.setJshj(orderDetail.getTaxAmount());
                jctyDdmx.setCjr(ddxx.getCjr());
                BigDecimal bhsje = InvoiceUtil.toBhsje(jctyDdmx.getJshj(), jctyDdmx.getSlzsl());
                jctyDdmx.setJe(bhsje);
                jctyDdmx.setSe(jctyDdmx.getJshj().subtract(jctyDdmx.getJe()));
                BigDecimal dj = InvoiceUtil.toBhsDj(jctyDdmx.getJshj(), jctyDdmx.getSlzsl(), jctyDdmx.getSl());
                jctyDdmx.setDj(dj);
                ddmxs.add(jctyDdmx);
                zjshj = zjshj.add(jctyDdmx.getJshj());
                zje = zje.add(jctyDdmx.getJe());
                zse = zse.add(jctyDdmx.getSe());
            }
            ddxx.setJshj(zjshj);
            ddxx.setJe(zje);
            ddxx.setSe(zse);
            ddxx.setDdlxDm(DdlxEnum.DDLX_NO_PAY.getDm());
            ddxx.setDdsj(LocalDateTime.now());
            ddxx.setOrderStatus(OrderStatusEnum.ZFCG.getDm());
            ddxx.setKpStatus(OrderKpStatusEnum.UNKNOWN.getDm());
            ddxx.setKpNotifyUrl(param.getCallBackUrl());
            ddxx.setBz(OrderUtil.bulidFxOrderBz(null));
            IssueBlueInvoiceResponse invoiceResponse = zfjkpPtCommonClient.issueBlueInvoice(param);
            if("0000".equals(invoiceResponse.getErrCode())){
          /*      boolean b = save(ddxx);
                if (b) {
                    jctyDdmxService.saveBatch(ddmxs);
                }*/
            }
            return invoiceResponse;

        } catch (Exception e) {
            log.error("创建订单失败:", e);
            response.setErrCode("9999");
            response.setErrInfo(e.getMessage());
            return response;
        }
    }
    /**
     * 查询订单状态
     *
     * @param param 参数
     * @return {@link QueryOrderStatusResponse }
     */
    @Override
    public QueryOrderStatusResponse queryOrderStatus(QueryOrderStatusRequest param) {

        return zfjkpPtCommonClient.queryOrderStatus(param);
    }

    /**
     * 下载发票
     *
     * @param param 参数
     * @return {@link DownloadInvoiceResponse }
     */
    @Override
    public DownloadInvoiceResponse downloadInvoice(DownloadInvoiceRequest param) {
        return zfjkpPtCommonClient.downloadInvoice(param);
    }

    /**
     * 替换发票
     *
     * @param param 参数
     * @return {@link ReplaceInvoiceResponse }
     */
    @Override
    public ReplaceInvoiceResponse replaceInvoice(FpttInfoVO param) {
        IdempotentUtil.verify("GBXU:" + param.getMerchantOrderId(), IdempotentUtil.IDEMPOTENT_TIME);
        log.info("国补小U发票换开入参：{}", JSONUtil.toJsonStr(param));
        return zfjkpPtCommonClient.replaceInvoice(param);
    }

    /**
     * 开具红色发票
     *
     * @param param 参数
     * @return {@link IssueRedInvoiceResponse }
     */
    @Override
    public IssueRedInvoiceResponse issueRedInvoice(IssueRedInvoiceRequest param) {

        return zfjkpPtCommonClient.issueRedInvoice(param);
    }


}

